﻿using Adp;
using Microsoft.AspNetCore.Mvc;
using Yqd.Models;
using System.Linq;
using Yqd.Controllers.Filter;
using Adp.Common;
using System;
using Yqd.Core;
using Yqd.Enm;
using System.Collections.Generic;

namespace Yqd.Controllers
{
    [Area("Yqd")]
    public class WxPlanflowController : Controller
    {
        YqdContext ctx;
        DdService ddService;

        public WxPlanflowController(YqdContext ctx, DdService ddService)
        {
            this.ctx = ctx;
            this.ddService = ddService;
        }

        [User]
        public ActionResult GetList()
        {
            var PlanID = Form.GetInt("PlanID");
            var data = ctx.Database.SqlQuery<Yqd_PlanFlow>("select * from Yqd_PlanFlow where PlanID={0} order by Instime asc", PlanID);
            var l = WxUser.LogonInfo;
            var ShowAdd = !data.Any() && l.Role.Any(it => it == 角色类型.管理员 || it == 角色类型.部门管理员);
            if (!ShowAdd)
            {
                var plan = ctx.Yqd_JobPlan.FirstOrDefault(it => it.PlanID == PlanID);
                if (plan != null && !plan.FlowIsOver)
                {
                    ShowAdd = data.Any(it => it.FlowMan == l.EmployeeCode) && !data.Any(it => it.EmployeeCode == l.EmployeeCode);
                }
            }
            var users = ctx.Yqd_User.Select(it => new { it.EmployeeCode, it.Name }).ToList();
            return this.ToJson(new
            {
                success = true,
                ShowAdd,
                totalcount = data.Count(),
                data = data.Select(it => new
                {
                    it.FlowID,
                    it.Opinion,
                    users.FirstOrDefault(m => m.EmployeeCode == it.EmployeeCode)?.Name,
                    NextName = users.FirstOrDefault(m => m.EmployeeCode == it.FlowMan)?.Name,
                    Instime = it.Instime.ToString("yyyy-MM-dd HH:mm:ss")
                })
            });
        }


        /// <summary>
        /// 添加内部流转
        /// </summary>
        /// <returns></returns>
        [User]
        public IActionResult Add(Yqd_PlanFlow model)
        {
            var SuperviseID = Form.GetInt("SuperviseID");
            var CoordinateID = Form.GetInt("CoordinateID");
            var eSuperviseID = Form.GetInt("eSuperviseID");
            var sSuperviseID = Form.GetInt("sSuperviseID");
            model.ItemID = SuperviseID;
            string headtitle = "";
            var IsJb = false;
            if (SuperviseID > 0)
            {
                var isExist = false;
                if (!isExist)
                {
                    var s = ctx.Yqd_Supervise.FirstOrDefault(it => it.SuperviseID == model.ItemID);
                    if (s != null)
                    {
                        headtitle = "领导督导";
                        model.ItemType = 事项类型.钉办督导;
                        isExist = true;
                        model.TaskID = s.TaskID;
                    }
                }
                if (!isExist)
                {
                    var c = ctx.Yqd_Coordinate.FirstOrDefault(it => it.CoordinateID == model.ItemID);
                    if (c != null)
                    {
                        headtitle = "领导协调";
                        model.ItemType = 事项类型.协同管理;
                        isExist = true;
                        model.TaskID = c.TaskID;
                    }
                }
                if (!isExist)
                {
                    var es = ctx.Yqd_ExactSupervise.FirstOrDefault(it => it.SuperviseID == model.ItemID);
                    if (es != null)
                    {
                        headtitle = "精准督查";
                        model.ItemType = 事项类型.精准督查;
                        isExist = true;
                        model.TaskID = es.TaskID;
                    }
                }
                if (!isExist)
                {
                    var ss = ctx.Yqd_SpecialSupervise.FirstOrDefault(it => it.SuperviseID == model.ItemID);
                    if (ss != null)
                    {
                        IsJb = true;
                        headtitle = ss.TaskType.ToString();
                        model.ItemType = ss.TaskType == 专项类型.专项交办 ? 事项类型.专项交办 : 事项类型.专项督查;
                        isExist = true;
                        model.TaskID = ss.TaskID;
                    }
                }
            }
            if (CoordinateID > 0)
            {
                model.ItemID = CoordinateID;
                model.ItemType = 事项类型.协同管理;
                var c = ctx.Yqd_Coordinate.FirstOrDefault(it => it.CoordinateID == model.ItemID);
                if (c != null)
                {
                    headtitle = "领导协调";
                    model.TaskID = c.TaskID;
                }
            }
            if (eSuperviseID > 0)
            {
                model.ItemID = eSuperviseID;
                model.ItemType = 事项类型.精准督查;
                var s = ctx.Yqd_ExactSupervise.FirstOrDefault(it => it.SuperviseID == model.ItemID);
                if (s != null)
                {
                    headtitle = "精准督查";
                    model.TaskID = s.TaskID;
                }
            }
            //if (sSuperviseID > 0)
            //{
            //    model.ItemID = sSuperviseID;
            //    model.ItemType = 事项类型.专项交办;
            //    headtitle = "专项交办";
            //}
            model.Instime = DateTime.Now;
            model.EmployeeCode = WxUser.LogonInfo.EmployeeCode;
            model.UnitCode = WxUser.LogonInfo.UnitCode;
            ctx.Yqd_PlanFlow.Add(model);
            var ret = ctx.SaveChanges();
            if (ret > 0)
            {
                WxUser.AddUser(new[] { model.FlowMan }, (int)角色类型.部门流转员);
                var l = WxUser.LogonInfo;
                // it.UnitCode == l.OrganizationCode && 
                var bl = ctx.Yqd_User.Any(it => it.EmployeeCode == model.FlowMan && ("," + it.Roles + ",").Contains("," + (int)角色类型.部门管理员 + ","));
                if (bl)
                {
                    ctx.Database.ExecuteSql("update Yqd_JobPlan set FlowIsOver=1 where PlanID={0};", model.PlanID);

                    //修改时间节点 todo:添加内部流转更新了反馈周期时间
                    var p = ctx.Yqd_JobPlan.Where(it => it.PlanID == model.PlanID).FirstOrDefault();
                    if (string.IsNullOrWhiteSpace(p.TimeLine))
                    {
                        var TimeLine = "";
                        var a = ctx.Yqd_Assign.FirstOrDefault(it => it.AssignID == p.AssignID);
                        if (a != null)
                        {
                            TimeLine = SuperviseService.GetFbLoopDate(a.FeedbackLoop, a.Instime, p.CompleteTime, a.Days);
                            ctx.Database.ExecuteSql("update Yqd_JobPlan set TimeLine={1} where PlanID={0}", p.PlanID, TimeLine);
                        }
                    }
                }
                var m = ctx.Yqd_User.FirstOrDefault(it => it.EmployeeCode == model.FlowMan);
                if (m != null && m.AccountId > 0)
                {
                    var TaskName = "";
                    if (model.ItemType == 事项类型.专项交办 || model.ItemType == 事项类型.专项督查)
                    {
                        var t = ctx.Yqd_SpecialTask.FirstOrDefault(it => it.TaskID == model.TaskID);
                        if (t != null) TaskName = t.Name;
                    }
                    else
                    {
                        var task = ctx.Yqd_Task.FirstOrDefault(it => it.TaskID == model.TaskID);
                        if (task != null) TaskName = task.TaskName;
                    }
                    var msg = ddService.Notification(new List<string> { m.AccountId.ToString() }, headtitle, model.TaskID.ToString(), "任务名称:" + TaskName, "您有一个任务需要流转，请您及时处理！", pushStep: 推送流程.内部流转, unitCode: WxUser.LogonInfo.UnitCode);
                    Logs.Warning<WxMySuperviseController>(WxUser.LogonInfo.Name + "发了内部流转工作通知，返回值：" + msg);
                }
                TaskLogService.AddLog(IsJb ? model.ItemID : model.TaskID, "填报了(" + model.Opinion + ")办理意见，下个流转人是" + m.Name + "。", IsJb);
            }
            return this.ToJson(new
            {
                success = true,
                ret
            });
        }

        [User]
        public ActionResult Delete()
        {
            var FlowID = Form.GetInt("FlowID");
            var flow = ctx.Yqd_PlanFlow.FirstOrDefault(it => it.FlowID == FlowID);
            var ret = ctx.Database.ExecuteSql("delete from Yqd_PlanFlow where FlowID={0};", FlowID);
            if (ret > 0)
            {
                var IsJb = flow.ItemType == 事项类型.专项交办;
                var TaskID = IsJb ? flow.ItemID : flow.TaskID;
                TaskLogService.AddLog(TaskID, "删除了办理意见(" + flow.Opinion + ")", IsJb);
            }
            return this.ToJson(new
            {
                success = true,
                ret
            });
        }
    }
}
